<template>
  <div class="pdf-preview-out">
    <div class="pdf_top_wrap">
      <div class="container_width pdf_top">
        <p class="arrow">
          <a
            :class="{ grey: currentPage == 1 }"
            @click="changePdfPage(0)"
            class="turn"
            >上一页</a
          >
          <el-input-number
            class="pdf_input"
            v-model="currentPage"
            @change="changePdfPage(2)"
            :min="1"
            :max="pageTotal"
            :controls="controls"
          ></el-input-number>

          / {{ pageTotal }}
          <a
            :class="{ grey: currentPage == pageTotal }"
            @click="changePdfPage(1)"
            class="turn"
            >下一页</a
          >
        </p>
        <div class="icon-scale">
          <el-button
            icon="el-icon-zoom-out"
            type="text"
            :disabled="pageScale - 0.1 < 0.3"
            @click="scalePage"
          >
          </el-button>
          <span>{{ pageScale * 100 }}%</span>
          <el-button
            icon="el-icon-zoom-in"
            type="text"
            :disabled="pageScale + 0.1 > 1"
            @click="scalePage('+')"
          >
          </el-button>
        </div>
      </div>
    </div>
    <!-- 上部 外层容器 用于滚动-->
    <div class="scroll-box">
      <!-- 用于截取调缩放后的空白区域 -->
      <div class="pdf-box">
        <!-- pdf预览区域(会被缩放) -->
        <div :style="getPdfSize()" class="pdf-scale-box">
          <!-- 预览组件 -->
          <pdf
            class="pdf_style"
            v-for="i in pageTotal"
            :page="i"
            :src="url"
            :id="'pdf' + i"
          >
          </pdf>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  window.addEventListener('contextmenu', function (e) {
  e.preventDefault();
});
// 插件引入
import pdf from "vue-pdf";
import { Loading } from "element-ui";
import CMapReaderFactory from "vue-pdf/src/CMapReaderFactory.js";
export default {
  components: {
    pdf,
  },
  props: {
    // pdf预览的地址 由父组件中传入 也可在本组件中直接赋值
    urlLink: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      controls: false,
      // 总页数
      pageTotal: 0,
      // 当前页
      currentPage: 1,
      // 缩放比例
      pageScale: 0.8,
      pageChangeTimer: null,
      url:'',
      loading:null
    };
  },
  created() {
    this.getTitlePdfurl();
  },
  methods: {
    getTitlePdfurl() {
      this.loading = Loading.service({
        lock: true,
        text: "正在加载中，请稍后...",
        background: "rgba(0, 0, 0, 0.3)",
      });

      this.url = pdf.createLoadingTask({ url: this.urlLink, CMapReaderFactory }); //解决中文乱码问题
      this.url.promise.then((pdf) => {
        this.pageTotal = pdf.numPages;
        this.loading.close()
      }).catch(err=>{
        this.loading.close()
           this.$message({
          message: "文件加载错误！",
          type: 'info'
        })
      })
    },

    // 改变PDF页码,val传过来区分上一页下一页的值,0上一页,1下一页
    changePdfPage(val) {
      if (val === 0 && this.currentPage > 1) {
        this.currentPage--;
      }
      if (val === 1 && this.currentPage < this.pageTotal) {
        this.currentPage++;
      }
      let idName = "#pdf" + this.currentPage;
      document.querySelector(idName).scrollIntoView(true);
    },
    // 获取到pdf总页数时触发 会传入总页数
    getTotalPage(page) {
      this.pageTotal = page;
    },
  
    // 每加载完成一页时触发(初始化/翻页时均会触发)
    pageLoaded() {
      // 重新设置pdf预览区域容器外容器的尺寸
      this.setPdfBoxSize();
    },
    // 设置pdf预览区域容器的缩放尺寸
    getPdfSize() {
      return {
        transform: `scale(${this.pageScale})`,
      };
    },
    // 点击缩放时触发
    scalePage(type) {
      // 改变缩放比例
      let sacle = 0;
      if (type === "+") {
        sacle = this.pageScale + 0.1;
      } else {
        sacle = this.pageScale - 0.1;
      }
      // 可能会涉及js的精度损失 保留一位小数即可
      this.pageScale = Number(sacle.toFixed(1));
      // 缩放后pdf预览区域容器中会有留白 重新设置pdf预览区域容器外容器的尺寸
      this.setPdfBoxSize();
    },
    // 方法 翻页
    chengPage(type) {
      // 防抖 0.5秒内不再次触发时执行
      if (this.pageChangeTimer) {
        clearTimeout(this.pageChangeTimer);
      }
      // 执行翻页
      this.pageChangeTimer = setTimeout(() => {
        if (type === "+") {
          this.currentPage += 1;
        } else {
          this.currentPage -= 1;
        }
        // 翻页后将滚动条归位到顶部
        this.scrollbarReset();
        this.pageChangeTimer = null;
      }, 500);
    },
    // 方法 滚动条归位到顶部
    scrollbarReset() {
      let boxDom = document.querySelector(".scroll-box");
      boxDom.scrollTop = 0;
    },
    // 方法 设置pdf预览区域容器外容器的尺寸
    setPdfBoxSize() {
      // 缩放后 pdf的显示上会缩小 但元素的实际占地尺寸不会变化(仍是原尺寸) 导致可能会出现部分区域留白 通过改变pdf预览区域容器外容器的尺寸 来将留白区域hidden
      // 获取pdf的原尺寸
      let boxDom = document.querySelector(".pdf-scale-box");
      // 获取要设置尺寸的元素dom
      let setDom = document.querySelector(".pdf-box");
      // 如有缩放 高度根据缩放比例变化(48px是预留的上下外边距)
      if (this.pageScale !== 1 && boxDom && setDom) {
        setDom.style.height = `${boxDom.clientHeight * this.pageScale + 48}px`;
      } else {
        setDom.style.height = "";
      }
    },
  },
};
</script>
<style lang="scss">
.pdf-preview-out {
  width: 100%;
  background-color: #ebe9ee;
  padding: 50px 0 30px;
  min-height: 100vh;
  user-select:none;
  -moz-user-select:none;
  -webkit-user-select:none;
  -ms-user-select:none;
  -khtml-user-select:none;
  -o-user-select:none;
  user-select:none;

  .pdf_top_wrap {
    position: fixed;
    top: 0;
    left: 0;
    height: 50px;
    background-color: #f9f9fa;
    border-bottom: 1px solid #ccc;
    width: 100%;
    z-index: 2;
    .pdf_top {
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .pdf_input {
        width: 50px;
        margin-left: 10px;
        .el-input__inner {
          border-color: #ccc;
          padding: 0;
          text-align: center;
          color: #000;
        }
      }

      .icon-scale {
        i {
          font-size: 22px;
          color: #000;
          margin: 0 8px;
          cursor: pointer;
        }
      }
      .arrow {
        cursor: pointer;
      }
    }
  }
  .scroll-box {
    height: calc(100% - 50px);
    overflow: auto;
    border-bottom: none;
    border-radius: 6px;
    &::-webkit-scrollbar {
      width: 10px;
    }
    &::-webkit-scrollbar-thumb {
      background-color: #c0d8f3;
      border-radius: 6px;
    }
    &::-webkit-scrollbar-track {
      background-color: transparent;
      border-radius: 6px;
    }
    .pdf-box {
      overflow: hidden;
      padding: 24px;
    }
    .pdf-scale-box {
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.3);
      transform-origin: center top;
      transition: 0.2s;
    }
  }

  .pdf_style {
    margin-bottom: 10px;
  }
}
</style>
